﻿using DevExpress.XtraEditors;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LSQL;
using Shopfloormanagement;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraExport.Helpers;
using DevExpress.XtraBars.Customization;
using DevExpress.XtraGrid.Columns;
using DevExpress.Xpo.Helpers;
using System.IO;
using DevExpress.Utils.Extensions;
using DevExpress.Charts.Native;
using DocumentFormat.OpenXml.Bibliography;
using DocumentFormat.OpenXml.Office.PowerPoint.Y2022.M03.Main;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraRichEdit.Model;
using Shopfloormanagement.PDCA;
using DevExpress.Utils.Text;
using DevExpress.Xpo.DB;
using ChartControlHelper;
using System.Management;
using DevExpress.Utils.Animation;
using System.Globalization;
using DevExpress.XtraGantt.Scheduling;
using DevExpress.XtraCharts;
using DevExpress.Pdf.Native;

namespace Shopfloormanagement
{
    public partial class rootcause : DevExpress.XtraEditors.XtraForm
    {
        public static string A3number;
        public static string PDCAnumber;
        public static rootcause instance = new rootcause();
        public rootcause()
        {
            InitializeComponent();
            A3number = "0";
            instance = this;
        }


        private void GridView1_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle < 0) return;

            for (int i = 1; i <= 9; i++)
            {
                if (e.Column.FieldName == $"Step{i}")

                {
                    var value = view.GetRowCellValue(e.RowHandle, e.Column);
                    if (value != null && int.TryParse(value.ToString(), out int stepVal))
                    {
                        switch (stepVal)
                        {
                            case 1:
                                e.Appearance.BackColor = Color.FromArgb(146, 208, 80);
                                break;
                            case 2:
                                e.Appearance.BackColor = Color.FromArgb(0, 176, 240);
                                break;
                            case 3:
                                e.Appearance.BackColor = Color.Red;
                                break;
                            case 4:
                                e.Appearance.BackColor = Color.FromArgb(234, 234, 234);
                                break;
                        }
                    }
                }
            }

        }//单元格根据状态变颜色
        private void GridView1_CustomColumnDisplayText(object sender, CustomColumnDisplayTextEventArgs e)
        {

            for (int i = 1; i <= 9; i++)
            {
                if (e.Column.FieldName == $"Step{i}")
                {
                    e.DisplayText = ""; // 不显示原始数字
                }

            }
        }//单元格根据状态变颜色
        private void SetColumnWidths(GridView view)
        {
            // 设置每个列的宽度
            SetColumnWidth(view, "A3ReportNumber", 150); // 设置 A3ReportNumber 列宽为 150
            SetColumnWidth(view, "A3ProblemStatement", 920); // 设置 A3ProblemStatement 列宽为 920
            SetColumnWidth(view, "Responsible", 150); // 设置 Responsible 列宽为 150

            // 设置 Step1 到 Step9 列宽为 70
            for (int i = 1; i <= 9; i++)
            {
                string colName = $"Step{i}";
                SetColumnWidth(view, colName, 70); // 设置 Step1 到 Step9 列宽为 70
            }



        }//设置列宽

        private void SetColumnWidth(GridView view, string columnName, int width)
        {
            // 获取列并设置宽度
            GridColumn column = view.Columns.ColumnByFieldName(columnName);
            if (column != null)
            {
                column.Width = width; // 设置列宽
            }
        }//设置列宽

        private void AddVisible()//修饰表格
        {
            //加载需要的列，并且修改显示名称
            A3list.Columns.AddVisible("A3ReportNumber", "A3 Report Number");
            A3list.Columns.AddVisible("A3ProblemStatement", "A3 Problem Statement");
            A3list.Columns.AddVisible("Responsible", "Responsible");
            A3list.Columns.AddVisible("Step1", "Step 1");
            A3list.Columns.AddVisible("Step2", "Step 2");
            A3list.Columns.AddVisible("Step3", "Step 3");
            A3list.Columns.AddVisible("Step4", "Step 4");
            A3list.Columns.AddVisible("Step5", "Step 5");
            A3list.Columns.AddVisible("Step6", "Step 6");
            A3list.Columns.AddVisible("Step7", "Step 7");
            A3list.Columns.AddVisible("Step8", "Step 8");
            A3list.Columns.AddVisible("Step9", "Step 9");
            //设置文本列不可编辑
            A3list.Columns["A3ReportNumber"].OptionsColumn.AllowEdit = false;
            A3list.Columns["A3ProblemStatement"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Responsible"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step1"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step2"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step3"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step4"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step5"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step6"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step7"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step8"].OptionsColumn.AllowEdit = false;
            A3list.Columns["Step9"].OptionsColumn.AllowEdit = false;
            //单元格根据状态变颜色
            GridView gridView1 = A3.MainView as GridView;
            if (gridView1 != null)
            {
                gridView1.RowCellStyle += GridView1_RowCellStyle;
                gridView1.CustomColumnDisplayText += GridView1_CustomColumnDisplayText;
            }
            // 禁用自动列宽，以便手动设置
            gridView1.OptionsView.ColumnAutoWidth = false;

            // 自定义设置每个列的宽度
            SetColumnWidths(gridView1);

        }

        private int clickSelect = 0;

        private int NewPerWeek = 0;
        public void lblActive_Click(object sender, EventArgs e)
        {
            clickSelect = 0;
            //点击Active显示下方绿条
            palActive.BackColor = Color.FromArgb(146, 208, 80);
            palOverdue.BackColor = Color.Transparent;
            palTotal.BackColor = Color.Transparent;
            //加载表格
            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and A3Status = 1 and Del_tag = 0");
            DataTable dtWeek = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and A3Status = 1 and Del_tag = 0 and (DATEPART(WEEK, Add_date) = DATEPART(WEEK, GETDATE()) AND DATEPART(YEAR, Add_date) = DATEPART(YEAR, GETDATE()))");
            NewPerWeek = dtWeek.Rows.Count;
            A3.DataSource = dt;
            A3list.OptionsView.ShowIndicator = false;
            A3list.Columns.Clear();
            AddVisible();
            lblActive.Text = dt.Rows.Count.ToString();



        }

        public void lblOverdue_Click(object sender, EventArgs e)
        {
            clickSelect = 1;
            //点击Overdue显示下方绿条
            palActive.BackColor = Color.Transparent;
            palOverdue.BackColor = Color.FromArgb(146, 208, 80);
            palTotal.BackColor = Color.Transparent;

            //加载表格
            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and A3Status = 1 and Del_tag = 0");
            List<int> idList = new List<int>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                idList.Add(Convert.ToInt32(dt.Rows[i]["ID"]));
            }
            if (idList.Count > 0)
            {
                string idListString = string.Join(",", idList);
                DataTable dt2 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_Step1", $"A3ReportNumberID IN({idListString}) and Duedate < '{DateTime.Now}'");
                List<int> idList2 = new List<int>();
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    idList2.Add(Convert.ToInt32(dt2.Rows[i]["A3ReportNumberID"]));

                }
                if (idList2.Count > 0)
                {
                    string idListString2 = string.Join(",", idList2);
                    DataTable dt3 = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"ID IN({idListString2})");
                    // 绑定到 GridControl
                    A3.DataSource = dt3;
                    lblOverdue.Text = dt3.Rows.Count.ToString();

                }
                else
                {
                    lblOverdue.Text = "0";
                    lblOverdue.Appearance.ForeColor = Color.Silver;
                }

            }
            else
            {
                lblOverdue.Text = "0";
                lblOverdue.Appearance.ForeColor = Color.Silver;
            }
            A3list.OptionsView.ShowIndicator = false;//取消显示行号
            A3list.Columns.Clear();
            AddVisible();

        }

        public void lblTotal_Click(object sender, EventArgs e)
        {
            clickSelect = 2;
            //点击Total显示下方绿条
            palActive.BackColor = Color.Transparent;
            palOverdue.BackColor = Color.Transparent;
            palTotal.BackColor = Color.FromArgb(146, 208, 80);
            //加载表格
            DataTable dt = LSQL.SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"FactoryID = {SystemInfo.readFactory}  and DepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
            A3.DataSource = dt;
            A3list.OptionsView.ShowIndicator = false;
            A3list.Columns.Clear();
            AddVisible();
            lblTotal.Text = dt.Rows.Count.ToString();

        }


        private void rootcause_Load(object sender, EventArgs e)
        {
            //测试后删除
            //SystemInfo.readFactory = 7;
            //SystemInfo.readDepartment = 40;
            lblOverdue_Click(sender, e);
            lblTotal_Click(sender, e);
            //进入后默认选择Active
            lblActive_Click(sender, e);
            A3list.DoubleClick += A3list_DoubleClick;//实现双击进入项目功能-绑定
            //xtraTabControl1.ShowTabHeader = DevExpress.Utils.DefaultBoolean.False;
            xtraTabControl1.TabPages.Remove(xtraTabPage2);

            CountPDCA();
            Load_Report_Count(xtraTabControl1.SelectedTabPageIndex);

            DateTime today = DateTime.Today;

            // 获取当前区域信息的 Calendar
            Calendar calendar = CultureInfo.CurrentCulture.Calendar;

            // 获取当前文化定义的“周起始日”
            CalendarWeekRule rule = CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule;
            DayOfWeek firstDay = CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;

            int weekNo = calendar.GetWeekOfYear(today, rule, firstDay);
            lbNewperweek.Text = $"New in CW{weekNo.ToString()}";


        }
        //实现双击进入项目功能
        private void A3list_DoubleClick(object sender, EventArgs e)
        {
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0)
            {
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null && selectedValue != DBNull.Value)
                {
                    A3number = selectedValue.ToString();
                    Step1 frm = new Step1();
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("选中记录的 ID 为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    A3number = selectedValue.ToString();

                    Step1 frm = new Step1();
                    frm.Show();

                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    A3number = selectedValue.ToString();
                    // 弹出确认对话框，询问是否继续操作
                    DialogResult result = MessageBox.Show("是否删除选中的A3?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    // 判断用户点击了“是”按钮
                    if (result == DialogResult.Yes)
                    {
                        // 执行操作
                        bool reslist = LSQL.SQL.Update(SystemInfo.SQL, "A3_List", "Del_tag = 1", $"ID = '{rootcause.A3number}'");
                        if (reslist)
                        {
                            MessageBox.Show("已删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            lblActive_Click(sender, e);
                            lblOverdue_Click(sender, e);
                            lblTotal_Click(sender, e);

                            switch (clickSelect)
                            {
                                case 0:
                                    lblActive_Click(sender, e);
                                    break;
                                case 1:
                                    lblOverdue_Click(sender, e);
                                    break;
                                case 2:
                                    lblTotal_Click(sender, e);
                                    break;
                                default:
                                    lblActive_Click(sender, e);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        // 用户点击了“否”，可以进行相应的处理，或者什么也不做
                        MessageBox.Show("操作已取消", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = A3list.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = A3list.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    A3number = selectedValue.ToString();

                    A3View frm = new A3View();
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (publicFunc.GetUserScope(SystemInfo.userID, SystemInfo.readparentDep) == false)
            {
                XtraMessageBox.Show("You have no permission");
                return;
            }

            DataTable dt = SQL.ReturnDataTableDist(SystemInfo.sys, "Codename", "Factories", $"ID = {SystemInfo.readFactory}");
            string code = dt.Rows[0]["Codename"].ToString();
            string datetime = DateTime.Now.ToString("yyMMdd");
            string condition = $"select count(*) as count from A3_List where FactoryID = {SystemInfo.readFactory} and DepartmentID = {SystemInfo.readparentDep}";
            DataTable dtCount = SQL.ReturnDataTable(SystemInfo.SQL, condition);
            int aa = (int)dtCount.Rows[0]["count"] + 1;
            string a3count;
            if (aa < 10)
            {
                a3count = $"0{aa}";
            }
            else
            {
                a3count = aa.ToString();
            }

            string A3code = code + datetime + a3count;

            string col = "FactoryID,DepartmentID,A3ReportNumber,Add_date";
            string value = $"{SystemInfo.readFactory},{SystemInfo.readparentDep},'{A3code}','{DateTime.Now.Date}'";
            int res = SQL.InsertReturnID(SystemInfo.SQL, "A3_list", col, value);
            if (res > 0)
            {
                int add = SQL.InsertReturnID(SystemInfo.SQL, "A3_Step1", "A3ReportNumberID", res.ToString());
                if (add > 0)
                {
                    XtraMessageBox.Show("成功将问题录入A3 list");
                    A3number = res.ToString();
                    Step1.instance.ShowDialog();
                }

            }
        }


        #region P D C A
        private void Load_PDCA(int idx)
        {
            DataTable[] dtArray = CountPDCA();
            DataTable dt = dtArray[idx];
            gcPDCA.DataSource = dt;
            PDCA_addvisible();
            gvPDCA.RowCellStyle += gvPDCA_RowCellStyle;
            gvPDCA.CustomColumnDisplayText += GvPDCA_CustomColumnDisplayText;

        }
        private void PDCA_addvisible()
        {
            gvPDCA.Columns.Clear();
            gvPDCA.Columns.AddVisible("PDCAnumber", "PDCA number");
            gvPDCA.Columns.AddVisible("ProblemStatement", "PDCA Problem statement");
            gvPDCA.Columns.AddVisible("ProblemType", "Problem types");
            gvPDCA.Columns.AddVisible("resperson", "Responsible");
            gvPDCA.Columns.AddVisible("P_status", "P");
            gvPDCA.Columns.AddVisible("D_status", "D");
            gvPDCA.Columns.AddVisible("C_status", "C");
            gvPDCA.Columns.AddVisible("A_status", "A");


            gvPDCA.Columns["PDCAnumber"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["ProblemStatement"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["ProblemType"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["resperson"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["P_status"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["D_status"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["C_status"].OptionsColumn.AllowEdit = false;
            gvPDCA.Columns["A_status"].OptionsColumn.AllowEdit = false;



        }


        private void btnPDCA_add_Click(object sender, EventArgs e)
        {
            PDCA.PDCA.isNewPDCA = true;
            DataTable dt = SQL.ReturnDataTableDist(SystemInfo.sys, "Codename", "Factories", $"ID = {SystemInfo.readFactory}");
            string code = dt.Rows[0]["Codename"].ToString();
            string datetime = DateTime.Now.ToString("yyMMdd");
            string condition = $"select count(*) as count from PDCA_View where DepartmentID = {SystemInfo.readparentDep}";

            DataTable dtCount = SQL.ReturnDataTable(SystemInfo.SQL, condition);
            int aa = (int)dtCount.Rows[0]["count"] + 1;
            string a3count;
            if (aa < 10)
            {
                a3count = $"0{aa}";
            }
            else
            {
                a3count = aa.ToString();
            }

            string PDCAcode = code + datetime + a3count;
            PDCA.PDCA.departmentID = SystemInfo.readparentDep;
            PDCA.PDCA.pdcaNumber = PDCAcode;
            PDCA.PDCA pdca = new PDCA.PDCA();
            pdca.ShowDialog();
        }

        private int lastPageIndex = -1;
        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            Load_Report_Count(xtraTabControl1.SelectedTabPageIndex);
            if (xtraTabControl1.SelectedTabPageIndex == lastPageIndex) return;

            lastPageIndex = xtraTabControl1.SelectedTabPageIndex;
            // 你的处理逻辑
            if (xtraTabControl1.SelectedTabPageIndex == 1)
            {
                Load_PDCA(0);

            }
        }

        private void gvPDCA_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            Console.WriteLine($"列名：{e.Column.FieldName}，值：{e.CellValue}");  // 或打断点
            // 你关注的列
            string[] targetColumns = { "P_status", "D_status", "C_status", "A_status" };

            if (!targetColumns.Contains(e.Column.FieldName))
                return;

            // 获取当前单元格的值（确保不是空值）
            object cellValue = gvPDCA.GetRowCellValue(e.RowHandle, e.Column);

            if (cellValue == null || !int.TryParse(cellValue.ToString(), out int statusValue))
                return;

            // 根据数值设置不同颜色
            switch (statusValue)
            {
                case 1:
                    e.Appearance.BackColor = Color.LightGreen;
                    break;
                case 2:
                    e.Appearance.BackColor = Color.LightYellow;
                    break;
                case 3:
                    e.Appearance.BackColor = Color.LightCoral;
                    break;
                case 4:
                    e.Appearance.BackColor = Color.LightGray;
                    break;
            }
        }

        private int selectPDCA = 0;
        private void gcPDCA_MouseClick(object sender, MouseEventArgs e)
        {
            int selectedRowHandle = gvPDCA.FocusedRowHandle;

            if (selectedRowHandle >= 0)
            {
                object selectedValue = gvPDCA.GetRowCellValue(selectedRowHandle, "PDCAnumber");
                object selectedValue1 = gvPDCA.GetRowCellValue(selectedRowHandle, "ID");
                DataTable dtRes = SQL.ReturnDataTableAsc(SystemInfo.SQL, "PDCA_P", $"PDCA_id = {Convert.ToInt32(selectedValue1)}");
                if (selectedValue != null && selectedValue != DBNull.Value)
                {
                    PDCAview.currP_id = (int)dtRes.Rows[0]["ID"];
                    PDCAview.currPDCAid = Convert.ToInt32(selectedValue1);
                    selectPDCA = Convert.ToInt32(selectedValue1);
                    //MessageBox.Show(PDCAview.currP_id.ToString());
                }
                else
                {
                    MessageBox.Show("选中记录的 ID 为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void gcPDCA_DoubleClick(object sender, EventArgs e)
        {

            int selectedRowHandle = gvPDCA.FocusedRowHandle;

            if (selectedRowHandle >= 0)
            {
                object selectedValue = gvPDCA.GetRowCellValue(selectedRowHandle, "PDCAnumber");
                object selectedValue1 = gvPDCA.GetRowCellValue(selectedRowHandle, "ID");
                DataTable dtRes = SQL.ReturnDataTableAsc(SystemInfo.SQL, "PDCA_P", $"PDCA_id = {Convert.ToInt32(selectedValue1)}");
                if (selectedValue != null && selectedValue != DBNull.Value)
                {
                    PDCA.PDCA.isNewPDCA = false;
                    PDCA.PDCA.pdcaID = Convert.ToInt32(selectedValue1);
                    PDCA.PDCA.curr_ID = (int)dtRes.Rows[0]["ID"];
                    PDCA.PDCA.pdcaNumber = selectedValue.ToString();
                    PDCA.PDCA frm = new PDCA.PDCA();
                    frm.Show();
                }
                else
                {
                    MessageBox.Show("选中记录的 ID 为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }

        }

        private void GvPDCA_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            string[] targetFields = { "P_status", "D_status", "C_status", "A_status" };

            if (targetFields.Contains(e.Column.FieldName))
            {
                switch (e.Value?.ToString())
                {
                    case "1":
                        e.DisplayText = "";
                        break;
                    case "2":
                        e.DisplayText = "";
                        break;
                    case "3":
                        e.DisplayText = "";
                        break;
                    case "4":
                        e.DisplayText = "";
                        break;
                }
            }
        }

        private DataTable[] CountPDCA()
        {
            string department = string.Empty;
            //更改为查询当前parent下所有部门的PDCA 
            if (SystemInfo.readparentDep == 0)
            {
                department = "0";
            }
            else
            {
                string query = $@"WITH DepartmentHierarchy AS (
    -- 基础查询
    SELECT 
        ID,
        DepartmentName,
        ParentDepartmentID,
        departmentLevel,
        1 as Level,
        CAST(DepartmentName as nvarchar(1000)) as Path
    FROM Departments
    WHERE ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0
    
    UNION ALL
    
    -- 递归部分
    SELECT 
        d.ID,
        d.DepartmentName,
        d.ParentDepartmentID,
        d.departmentLevel,
        dh.Level + 1,
        CAST(dh.Path + ' > ' + d.DepartmentName as nvarchar(1000))
    FROM Departments d
    INNER JOIN DepartmentHierarchy dh ON d.ParentDepartmentID = dh.ID
    WHERE d.Del_tag = 0
)
SELECT 
    ID,
    DepartmentName,
    ParentDepartmentID,
    departmentLevel,
    Level as HierarchyLevel,
    Path as DepartmentPath
FROM DepartmentHierarchy
ORDER BY Level, ID;";
                DataTable dtDep = SQL.ReturnDataTable(SystemInfo.SQL, query);
                string[] depArray = new string[dtDep.Rows.Count];
                for (int i = 0; i < dtDep.Rows.Count; i++)
                {
                    depArray[i] = dtDep.Rows[i]["ID"].ToString();
                }
                department = string.Join(",", depArray) + $",{SystemInfo.readparentDep}";
            }

            DataTable dtActive = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID in ({department}) and ComplainDate >= '{DateTime.Now.Date}' and isComplete = 0");
            DataTable dtActiveWeek = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID in ({department}) and ComplainDate >= '{DateTime.Now.Date}' and isComplete = 0 and (DATEPART(WEEK, Create_date) = DATEPART(WEEK, GETDATE()) AND DATEPART(YEAR, Create_date) = DATEPART(YEAR, GETDATE()))");
            DataTable dtOver = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID in ({department}) and ComplainDate < '{DateTime.Now.Date}' and isComplete = 0");
            DataTable dtTotal = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID in ({department})");

            PDCAperweek = dtActiveWeek.Rows.Count;
            int active = dtActive.Rows.Count;
            int over = dtOver.Rows.Count;
            int total = dtTotal.Rows.Count;

            lbP_active.Text = active.ToString();
            lbP_over.Text = over.ToString();
            lbP_Total.Text = total.ToString();

            DataTable[] dtArray = new DataTable[3];
            dtArray[0] = dtActive;
            dtArray[1] = dtOver;
            dtArray[2] = dtTotal;

            return dtArray;

        }

        private int pdcaSelect = 0;

        private int PDCAperweek = 0;
        private void lbP_active_Click(object sender, EventArgs e)
        {
            pdcaSelect = 0;
            //点击Active显示下方绿条
            plP_active.BackColor = Color.FromArgb(146, 208, 80);
            plP_Over.BackColor = Color.Transparent;
            plP_Total.BackColor = Color.Transparent;
            Load_PDCA(0);
        }

        private void lbP_over_Click(object sender, EventArgs e)
        {
            pdcaSelect = 1;
            //点击Active显示下方绿条
            plP_active.BackColor = Color.Transparent;
            plP_Over.BackColor = Color.FromArgb(146, 208, 80);
            plP_Total.BackColor = Color.Transparent;
            Load_PDCA(1);
        }

        private void lbP_Total_Click(object sender, EventArgs e)
        {
            pdcaSelect = 2;
            //点击Active显示下方绿条
            plP_active.BackColor = Color.Transparent;
            plP_Over.BackColor = Color.Transparent;
            plP_Total.BackColor = Color.FromArgb(146, 208, 80);
            Load_PDCA(2);
        }

        public static string PDCA_tag = "";
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            // 获取选中行的索引
            int selectedRowHandle = gvPDCA.FocusedRowHandle;

            if (selectedRowHandle >= 0) // 确保有选中行
            {
                // 假设你要保存的列名是 "ColumnName"，请替换为你的实际列名
                object selectedValue = gvPDCA.GetRowCellValue(selectedRowHandle, "ID");

                if (selectedValue != null)
                {
                    PDCA_tag = selectedValue.ToString();
                    // 弹出确认对话框，询问是否继续操作
                    DialogResult result = MessageBox.Show("是否删除选中的PDCA?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    // 判断用户点击了“是”按钮
                    if (result == DialogResult.Yes)
                    {
                        // 执行操作
                        bool reslist = LSQL.SQL.Update(SystemInfo.SQL, "PDCA_view", "Del_tag = 1", $"ID = '{rootcause.PDCA_tag}'");
                        if (reslist)
                        {
                            MessageBox.Show("已删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            lbP_active_Click(sender, e);
                            lbP_over_Click(sender, e);
                            lbP_Total_Click(sender, e);

                            switch (pdcaSelect)
                            {
                                case 0:
                                    lbP_active_Click(sender, e);
                                    break;
                                case 1:
                                    lbP_over_Click(sender, e);
                                    break;
                                case 2:
                                    lbP_Total_Click(sender, e);
                                    break;
                                default:
                                    lbP_active_Click(sender, e);
                                    break;
                            }
                        }
                    }
                    else
                    {
                        // 用户点击了“否”，可以进行相应的处理，或者什么也不做
                        MessageBox.Show("操作已取消", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
                else
                {
                    MessageBox.Show("选中的列数据为空！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("请先选择一条记录！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region Root cause KPI report

        private void Load_Report_Count(int tabIndex)
        {
            if (tabIndex == 0)//此时是A3
            {
                decimal total = Convert.ToDecimal(lblTotal.Text);
                decimal overdue = Convert.ToDecimal(lblOverdue.Text);
                decimal comple;
                decimal over;
                if (total == 0)
                {
                    comple = 0;
                    over = 0;
                }
                else
                {
                    comple = Math.Round((total - overdue) * 100 / total, 2);
                    over = Math.Round(overdue * 100 / total, 2);
                }
                  

                
                lbA3new.Text = NewPerWeek.ToString();
                lbA3comple.Text = Convert.ToString(comple) + "%";
                lbA3over.Text = Convert.ToString(over) + "%";
            }
            if (tabIndex == 1)//此时是PDCA
            {
                decimal total = Convert.ToDecimal(lbP_Total.Text);
                decimal overdue = Convert.ToDecimal(lbP_over.Text);
                decimal comple;
                decimal over;
                if (total == 0)
                {
                    comple = 0;
                    over = 0;
                }
                else
                {
                    comple = Math.Round((total - overdue) * 100 / total, 2);
                    over = Math.Round(overdue * 100 / total, 2);
                }
                   
                
                lbPDCAnew.Text = NewPerWeek.ToString();
                lbPDCAcomple.Text = Convert.ToString(comple) + "%";
                lbPDCAover.Text = Convert.ToString(over) + "%";
            }
        }

        private void Count_A3()
        {
            int level = 4;
            if (SystemInfo.readparentDep != 0)
            {
                level = SystemInfo.readLevel - 1;

                DataTable dtDep = SQL.ReturnDataTableAsc(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
                int[] depArray = new int[dtDep.Rows.Count];

                var department = new List<string>();
                var A3count = new List<double>();
                var comp = new List<double>();
                var over = new List<double>();
                if (dtDep.Rows.Count > 0)
                {
                    for (int i = 0; i < depArray.Length; i++)
                    {
                        depArray[i] = (int)dtDep.Rows[i]["ID"];
                        int DepID = (int)dtDep.Rows[i]["ID"];
                        department.Add(dtDep.Rows[i]["DepartmentName"].ToString());

                        DataTable res = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DATEPART(WEEK,Add_date) = DATEPART(WEEK,GETDATE()) and  DATEPART(YEAR, Add_date) = DATEPART(YEAR, GETDATE()) and DepartmentID = {DepID}");

                        //计算完成率
                        DataTable total = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0");
                        DataTable complete = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0 and A3status = 1");
                        DataTable overdue = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0 and A3status = 3");

                        comp.Add(Convert.ToDouble((double)complete.Rows.Count / total.Rows.Count));
                        over.Add(Convert.ToDouble((double)overdue.Rows.Count / total.Rows.Count));
                        A3count.Add(Convert.ToDouble(res.Rows.Count));
                    }
                }

                ChartControlHelper.ChartControlHelper.SetChartData(chartNew, department, A3count);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartComletation, department, comp, "", ViewType.Line,decimalPlaces: 1, multiplyBy100: true);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartOverdue, department, over, "", ViewType.Line,decimalPlaces: 1, multiplyBy100: true);
            }
            else
            {
                DataTable dtDep = SQL.ReturnDataTableAsc(SystemInfo.SQL, "Departments", $"ParentDepartmentID = 0 and Del_tag = 0");
                int[] depArray = new int[dtDep.Rows.Count];
                var department = new List<string>();
                var A3count = new List<double>();
                var comp = new List<double>();
                var over = new List<double>();
                if (dtDep.Rows.Count > 0)
                {
                    for (int i = 0; i < depArray.Length; i++)
                    {
                        depArray[i] = (int)dtDep.Rows[i]["ID"];
                        int DepID = (int)dtDep.Rows[i]["ID"];
                        department.Add(dtDep.Rows[i]["DepartmentName"].ToString());

                        DataTable res = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DATEPART(WEEK,Add_date) = DATEPART(WEEK,GETDATE()) and  DATEPART(YEAR, Add_date) = DATEPART(YEAR, GETDATE()) and DepartmentID = {(int)dtDep.Rows[i]["ID"]}");
                        //计算完成率
                        DataTable total = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0");
                        DataTable complete = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0 and A3status = 1");
                        DataTable overdue = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_List", $"DepartmentID = {DepID} and Del_tag = 0 and A3status = 3");

                        comp.Add(Convert.ToDouble((double)complete.Rows.Count / total.Rows.Count));
                        over.Add(Convert.ToDouble((double)overdue.Rows.Count / total.Rows.Count));

                        A3count.Add(Convert.ToDouble(res.Rows.Count));
                    }
                }

                ChartControlHelper.ChartControlHelper.SetChartData(chartNew, department, A3count);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartComletation, department, comp, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartOverdue, department, over, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
            }

            


        }

        private void Count_PDCA()
        {
            int level = 4;
            if (SystemInfo.readparentDep != 0)
            {
                level = SystemInfo.readLevel - 1;

                DataTable dtDep = SQL.ReturnDataTableAsc(SystemInfo.SQL, "Departments", $"ParentDepartmentID = {SystemInfo.readparentDep} and Del_tag = 0");
                int[] depArray = new int[dtDep.Rows.Count];

                var department = new List<string>();
                var A3count = new List<double>();
                var comp = new List<double>();
                var over = new List<double>();
                if (dtDep.Rows.Count > 0)
                {
                    for (int i = 0; i < depArray.Length; i++)
                    {
                        depArray[i] = (int)dtDep.Rows[i]["ID"];
                        int DepID = (int)dtDep.Rows[i]["ID"];
                        department.Add(dtDep.Rows[i]["DepartmentName"].ToString());

                        DataTable res = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DATEPART(WEEK,Create_date) = DATEPART(WEEK,GETDATE()) and  DATEPART(YEAR, Create_date) = DATEPART(YEAR, GETDATE()) and DepartmentID = {DepID}");

                        //计算完成率
                        DataTable total = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID = {DepID}");
                        DataTable complete = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID = {DepID} and isComplete = 1");
                        DataTable overdue = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_View_PDCAviewList", $"DepartmentID = {DepID} and isComplete = 0 and ComplainDate < GETDATE()");

                        comp.Add(Convert.ToDouble((double)complete.Rows.Count / total.Rows.Count));
                        over.Add(Convert.ToDouble((double)overdue.Rows.Count / total.Rows.Count));
                        A3count.Add(Convert.ToDouble(res.Rows.Count));
                    }
                }

                ChartControlHelper.ChartControlHelper.SetChartData(chartNew, department, A3count);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartComletation, department, comp, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartOverdue, department, over, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
            }
            else
            {
                DataTable dtDep = SQL.ReturnDataTableAsc(SystemInfo.SQL, "Departments", $"ParentDepartmentID = 0 and Del_tag = 0");
                int[] depArray = new int[dtDep.Rows.Count];
                var department = new List<string>();
                var A3count = new List<double>();
                var comp = new List<double>();
                var over = new List<double>();
                if (dtDep.Rows.Count > 0)
                {
                    for (int i = 0; i < depArray.Length; i++)
                    {
                        depArray[i] = (int)dtDep.Rows[i]["ID"];
                        int DepID = (int)dtDep.Rows[i]["ID"];
                        department.Add(dtDep.Rows[i]["DepartmentName"].ToString());

                        DataTable res = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DATEPART(WEEK,Create_date) = DATEPART(WEEK,GETDATE()) and  DATEPART(YEAR, Create_date) = DATEPART(YEAR, GETDATE()) and DepartmentID = {(int)dtDep.Rows[i]["ID"]}");
                        //计算完成率
                        DataTable total = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID = {DepID}");
                        DataTable complete = SQL.ReturnDataTableAsc(SystemInfo.SQL, "View_PDCAview", $"DepartmentID = {DepID} and isComplete = 1");
                        DataTable overdue = SQL.ReturnDataTableAsc(SystemInfo.SQL, "A3_View_PDCAviewList", $"DepartmentID = {DepID} and isComplete = 0 and ComplainDate < GETDATE()");

                        comp.Add(Convert.ToDouble((double)complete.Rows.Count / total.Rows.Count));
                        over.Add(Convert.ToDouble((double)overdue.Rows.Count / total.Rows.Count));
                        A3count.Add(Convert.ToDouble(res.Rows.Count));
                    }
                }

                ChartControlHelper.ChartControlHelper.SetChartData(chartNew, department, A3count);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartComletation, department, comp, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
                ChartControlHelper.ChartControlHelper.SetChartDataWithPercentage(chartOverdue, department, over, "", ViewType.Line, decimalPlaces: 1, multiplyBy100: true);
            }




        }

        #endregion

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            Count_A3();
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            Count_PDCA();
        }

        private void btnKPI_Click(object sender, EventArgs e)
        {
            xtraTabControl1.SelectedTabPageIndex = 2;
            Count_A3();
        }

        private void btnP_KPI_Click(object sender, EventArgs e)
        {
            xtraTabControl1.SelectedTabPageIndex = 2;
            Count_PDCA();
        }

        private void btnPDCAview_Click(object sender, EventArgs e)
        {
            if (PDCAview.currP_id == 0)
            {
                MessageBox.Show("未选择PDCA，请返回选择");
                return;
            }

            PDCAview view = new PDCAview();
            view.ShowDialog();
        }

        private void btnClosePDCA_Click(object sender, EventArgs e)
        {
            if (!publicFunc.GetUserScope(SystemInfo.userID, SystemInfo.readDepartment) && !publicFunc.GetUserSuper(SystemInfo.userID))
            {
                MessageBox.Show("You have no permisson");
                return;
            }
            if(selectPDCA == 0)
            {
                MessageBox.Show("Please select a PDCA");
            }
            DialogResult dialog = MessageBox.Show("是否关闭PDCA？", "是否关闭…", MessageBoxButtons.OKCancel);
            if (dialog == DialogResult.OK)
            {
                bool update = SQL.Update(SystemInfo.SQL, "PDCA_view", "isComplete = 1", $"ID = {selectPDCA}");
                if (update)
                {
                    MessageBox.Show("成功关闭");
                }
            }
        }
    }
}